import React from 'react';
import { Form, Card, Button, Table, Tag, message, Anchor, Row, Col } from 'antd';
import { history } from 'umi'
import { connect } from 'umi';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FileUpload from '@/components/Custom/FileUpload';
import ColorPicker from '@/components/ColorPicker';
import moment from 'moment';
import { get as getPath } from 'object-path';
import authHelper from '@/utils/auth/helper';
import CityPicker from '@/components/CityPicker';
import { eventTrack } from '@/utils/track';
import { getTabContainer } from '@/utils/utils';

import { BaseWrapper } from '../components';
import { getCompanyDetail } from '../services';
import { AUDIT } from '../constant';
import styles from './index.less';

const { checkCode } = authHelper;

const CompanyDetail = ({ location, dictionary, dispatch }) => {
    const { query } = location;
    const { industryType } = dictionary;
    // console.log('CompanyDetail -> industryType', industryType);
    const [loading, setLoading] = React.useState(false);
    const [info, setInfo] = React.useState({});
    const [logoFile, setLogoFile] = React.useState([]);
    const [licenseFile, setLicenseFile] = React.useState([]);

    const { organizationType } = info;

    const getDetail = async () => {
        setLoading(true);
        const res = await getCompanyDetail(query && query.organizationCode);
        setLoading(false);
        const { data, code, msg } = res;
        if (code === 10000) {
            // console.log(data);
            setInfo(data);
            const logo = getPath(data, 'logoFile', []);
            const license = getPath(data, 'licenseFile', []);
            if (logo && logo.length > 0) {
                setLogoFile([
                    {
                        uid: logo[0].keyName,
                        keyName: logo[0].keyName,
                        name: logo[0].originName,
                        oldName: logo[0].originName,
                        url: logo[0].url
                    }
                ]);
            }
            if (license && license.length > 0) {
                setLicenseFile([
                    {
                        uid: license[0].keyName,
                        keyName: license[0].keyName,
                        name: license[0].originName,
                        oldName: license[0].originName,
                        url: license[0].url
                    }
                ]);
            }
        } else {
            message.error(msg);
            history.push('/');
        }
    };
    const orgTitle = getPath(info, 'organizationType', '') === 1 ? '集团' : '公司';
    const isSingapore = getPath(info, 'area', '').includes('Singapore');

    React.useEffect(() => {
        dispatch({
            type: 'dictionary/fetchDictionaryList',
            payload: {
                codes: ['industryType']
            }
        });
        getDetail();
    }, []);

    const getIndustry = () => {
        const type = getPath(info, 'industry', '');
        if (type && industryType.length > 0) {
            const tempArr = industryType.filter(item => item.dictValue === type);
            return tempArr.length > 0 ? tempArr[0].dictName : '';
        }
        return '';
    };

    const baseInfo1 = [
        {
            key: `${orgTitle}名称(中文)`,
            value: getPath(info, 'organizationName', '')
        },
        {
            key: `${orgTitle}名称(英文)`,
            value: getPath(info, 'organizationNameEnglish', '')
        },
        {
            key: '主题色',
            value: <ColorPicker value={getPath(info, 'colorCode')} readOnly />
        },
        {
            key: '排序号',
            value: getPath(info, 'sort', ''),
            hide: getPath(info, 'organizationType', '') === 1
        }
    ];

    const baseInfo2 = [
        {
            key: '是否助理团',
            value: getPath(info, 'assistantFlag', '') === 1 ? '是' : '否',
            hide: getPath(info, 'organizationType', '') === 1
        },
        {
            key: '关联机构',
            value: getPath(info, 'relativeOrganizations', [])
                .map(item => item.organizationName)
                .join('、'),
            hide: getPath(info, 'organizationType', '') === 1
        }
    ];

    const baseInfo3 = [
        {
            key: '上级机构',
            value: getPath(info, 'parentOrganizationName', ''),
            hide: getPath(info, 'organizationType', '') === 1
        },
        {
            key: '国家/地区',
            value: <CityPicker showOnly valueType="codeArray" value={getPath(info, 'area', '').split(',') || []} />
        },
        {
            key: `${orgTitle}简介(中文)`,
            value: getPath(info, 'organizationDesc', '')
        },
        {
            key: `${orgTitle}简介(英文)`,
            value: getPath(info, 'organizationDescEnglish', '')
        },
        {
            key: `${orgTitle}logo`,
            value:
                logoFile && logoFile.length > 0 ? (
                    <FileUpload isSingle value={{ allFileList: logoFile }} disabled />
                ) : (
                    ''
                )
        }
    ];

    let baseInfoList = [...baseInfo1];

    if (organizationType === 3) {
        baseInfoList = [...baseInfoList, ...baseInfo2];
    }

    baseInfoList = [...baseInfoList, ...baseInfo3];

    const otherInfoList = [
        {
            key: '法人代表',
            value: getPath(info, 'legalRepresentative', '')
        },
        {
            key: isSingapore ? 'UEN' : '统一社会信用代码',
            value: getPath(info, 'licenseCode', '')
        },
        {
            key: isSingapore ? 'UEN证件照片' : '营业执照照片',
            value:
                licenseFile && licenseFile.length > 0 ? (
                    <FileUpload isSingle value={{ allFileList: licenseFile }} disabled />
                ) : (
                    ''
                )
        },
        {
            key: '联系电话',
            value: getPath(info, 'phone', '')
        },
        {
            key: '邮政编码',
            value: getPath(info, 'postalcode', '')
        },
        {
            key: '官网地址',
            value: getPath(info, 'websiteAddress', '')
        },
        {
            key: '所属行业',
            value: getIndustry()
        },
        {
            key: '经营范围(中文)',
            value: getPath(info, 'business', '')
        },
        {
            key: '经营范围(英文)',
            value: getPath(info, 'businessEnglish', '')
        },
        {
            key: '注册邮箱',
            value: getPath(info, 'email', ''),
            hide: getPath(info, 'organizationType', '') !== 1
        },
        {
            key: '创建时间',
            value: getPath(info, 'regTime', '') ? moment(getPath(info, 'regTime', '')).format('YYYY年MM月DD日') : ''
        }
    ];
    const currencyText = getPath(info, 'currencyText', '') ? `（${getPath(info, 'currencyText', '')}）` : '';
    const financialList = [
        {
            key: '默认结算货币',
            value: `${getPath(info, 'currencyCode', '')}${currencyText}`
        }
    ];
    const renderBlock = arr =>
        arr.map(item => (
            <Form.Item label={item.key} key={item.key} style={{ margin: 0 }}>
                <div style={{ wordBreak: 'break-all' }}>{item.value}</div>
            </Form.Item>
        ));

    const columns = [
        {
            title: '名称',
            dataIndex: 'addressName',
            width: '20%'
        },
        {
            title: '所在地区',
            dataIndex: 'area',
            render: text => <CityPicker showOnly valueType="codeArray" value={text?.split(',') || []} />,
            width: '25%'
        },
        {
            title: '详细地址',
            dataIndex: 'addressDetail',
            render: (text, record) => {
                if (record.isDefault) {
                    return (
                        <>
                            <span>{text}</span>
                            <Tag color="orange" style={{ marginLeft: 10 }}>
                                通讯地址
                            </Tag>
                        </>
                    );
                }
                return text;
            }
            // width: '40%'
        }
    ];
    return (
        <PageHeaderWrapper>
            <Card
                title={
                    <>
                        {`${orgTitle}信息`}
                        {getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2 && (
                            <Tag color="orange" style={{ marginLeft: 10 }}>
                                {AUDIT[getPath(info, 'auditStatus', '')]}
                            </Tag>
                        )}
                    </>
                }
                bordered={false}
                loading={loading}
                extra={
                    getPath(info, 'organizationPermissions', '') === 1 &&
                    checkCode('office:orgs:organization:edit') && (
                        <Button
                            type="primary"
                            disabled={
                                getPath(info, 'auditStatus') !== undefined && getPath(info, 'auditStatus', '') !== 2
                            }
                            onClick={async () => {
                                await eventTrack({
                                    eventName: 'personnel_management_organization_company_manage_info_edit_click',
                                    pageName: 'personnel_management_organization',
                                    eventProps: {
                                        click_context: `${query.organizationName}-编辑`
                                    }
                                });
                                history.push({
                                    pathname: '/office/personnelManagement/organization/companyedit',
                                    query: {
                                        organizationCode: query && query.organizationCode,
                                        organizationPath: query && query.organizationPath,
                                        organizationName: query && query.organizationName
                                    }
                                });
                            }}
                        >
                            编辑
                        </Button>
                    )
                }
            >
                <Row gutter={24}>
                    <Col span={21}>
                        <BaseWrapper id="BasicInfo" title="基本信息" className={styles.formWrap}>
                            <Form>{renderBlock(baseInfoList.filter(item => !item.hide))}</Form>
                        </BaseWrapper>
                        <BaseWrapper id="OtherInfo" title="其他信息" className={styles.formWrap}>
                            <Form>{renderBlock(otherInfoList.filter(item => !item.hide))}</Form>
                        </BaseWrapper>
                        <BaseWrapper id="Address" title="办公地点">
                            <Table
                                bordered={false}
                                dataSource={getPath(info, 'addressDtoList', [])}
                                columns={columns}
                                pagination={false}
                                rowKey="addressCode"
                            />
                        </BaseWrapper>
                        <br />
                        <BaseWrapper id="financialInfo" title="财务信息" className={styles.formWrap}>
                            <Form>{renderBlock(financialList.filter(item => !item.hide))}</Form>
                        </BaseWrapper>
                    </Col>
                    <Col span={3}>
                        <div style={{ position: 'relative' }}>
                            <Anchor affix showInkInFixed targetOffset={50} getContainer={() => getTabContainer()}>
                                <Anchor.Link href="#BasicInfo" title="基本信息" />
                                <Anchor.Link href="#OtherInfo" title="其他信息" />
                                <Anchor.Link href="#Address" title="办公地点" />
                                <Anchor.Link href="#financialInfo" title="财务信息" />
                            </Anchor>
                        </div>
                    </Col>
                </Row>
            </Card>
        </PageHeaderWrapper>
    );
};

export default connect(({ dictionary }) => ({
    dictionary
}))(CompanyDetail);
